package api

import (
	"cloud-entropy-storage-system/common/pkg/msg"
	"cloud-entropy-storage-system/common/pkg/resp"
	"cloud-entropy-storage-system/server/internal/config"
	"cloud-entropy-storage-system/server/internal/svc"
	"cloud-entropy-storage-system/server/internal/types/form"
	"cloud-entropy-storage-system/server/model/dir"
	"github.com/asdine/storm/v3"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

type DirLogic struct {
	log    *zap.Logger
	svcCtx *svc.DirSvc
	cfg    config.Config
	db     *storm.DB
}

func NewDirLogic(log *zap.Logger, cfg config.Config, db *storm.DB) *DirLogic {
	return &DirLogic{log: log, cfg: cfg, svcCtx: svc.NewDirSvc(log, dir.NewOperate(db))}
}

func (d *DirLogic) List() gin.HandlerFunc {
	return func(c *gin.Context) {
		page, _ := strconv.Atoi(c.DefaultQuery("page", "0"))
		limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
		data, err := d.svcCtx.List(page, limit)
		if err != nil {
			resp.ErrorResp(c).SetMsg(err.Error()).WriteErrJsonExit(http.StatusInternalServerError)
			return
		}
		resp.SuccessResp(c).SetCode(0).SetCount(d.svcCtx.Count()).SetData(data).WriteJsonExit()
	}
}

func (d *DirLogic) Set() gin.HandlerFunc {
	return func(c *gin.Context) {
		var f form.Dir
		if err := c.Bind(&f); err != nil {
			resp.ErrorResp(c).SetMsg(msg.GetMsg(msg.FormRequiredErr)).WriteJsonExit()
			return
		}
		if err := d.svcCtx.Set(f); err != nil {
			resp.ErrorResp(c).SetMsg(err.Error()).WriteJsonExit()
			return
		}
		resp.SuccessResp(c).WriteJsonExit()
	}
}

func (d *DirLogic) Delete() gin.HandlerFunc {
	return func(c *gin.Context) {
		var f form.DelDir
		if err := c.Bind(&f); err != nil {
			resp.ErrorResp(c).SetMsg(msg.GetMsg(msg.FormRequiredErr)).WriteJsonExit()
			return
		}
		if err := d.svcCtx.Delete(f.ID); err != nil {
			resp.ErrorResp(c).SetMsg(err.Error()).WriteJsonExit()
			return
		}
		resp.SuccessResp(c).WriteJsonExit()
	}
}
